<template>
  <div class="title">当前项目ID：{{ route.query.tid }}</div>
  <div class="flex">
    <div>
      <a-button type="link" v-show="selectedRowKeys.length > 0" @click="onBatchPush">批量推送</a-button>
    </div>
    <a-button type="primary" @click="onAdd">新增配额组</a-button>
  </div>
  <a-table bordered :data-source="dataSource" :columns="columns" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
    <template #bodyCell="{ column, text, record }">
      <template v-if="column.dataIndex === 'requiredCompletes'">
        <a-input-number placeholder="请输入目标数量" style="width: 100%;" v-if="editableData[record.key]" v-model:value="editableData[record.key].requiredCompletes" />
        <span v-else>{{ text }}</span>
      </template>
      <template v-if="column.dataIndex === 'questions'">
        <a-tag v-for="(item,index) in text" :key="item.label" :closable="!!editableData[record.key]" @close="onDeleteQuestion(record.key, index)" style="margin-bottom: 6px;">
          {{ item.label }}
        </a-tag>
        <a-button type="link" @click="onOpenModal(record.key, record.id)" v-if="editableData[record.key]"><template #icon><plus-outlined /></template>点击添加问题</a-button>
      </template>
      <template v-else-if="column.dataIndex === 'operation'">
        <template v-if="editableData[record.key]"><a @click="onSave(record.key)">保存</a></template>
        <template v-else>
          <a @click="onEdit(record.key)">修改</a>
          <a class="btn" @click="onMatch(record.key)">匹配</a>
          <a class="btn" @click="onPush(record.key)">推送</a>
          <a-popconfirm
              title="确认删除?"
              @confirm="onDelete(record.key)"
            >
            <a class="btn">删除</a>
          </a-popconfirm>
        </template>
      </template>
    </template>
  </a-table>
  <BasicModal @register="register">
    <a-select v-model:value="modalState.question" placeholder="请选择抽样问题" style="width: 100%;margin-bottom: 24px;" @change="setInitModal">
      <a-select-option :value="option.id" v-for="option in modalState.questionOptions" :key="option.id">{{ option.name }}</a-select-option>
    </a-select>
    <a-checkbox-group v-model:value="modalState.checkbox" v-if="modalType === 'checkbox'">
      <a-row style="margin-bottom: 8px;" v-for="option in modalOptions" :key="option.value">
        <a-checkbox :value="option.value">{{ option.label }}</a-checkbox>
      </a-row>
    </a-checkbox-group>
    <a-tree checkable v-else-if="modalType === 'tree'" v-model:checkedKeys="modalState.tree" :tree-data="modalOptions" :field-names="{children:'list', title:'name', key:'id' }" />
    <a-textarea v-model:value="modalState.textarea" v-else-if="modalType === 'textarea'" placeholder="请输入，多个用逗号隔开" :rows="4" />
    <a-row v-else-if="modalType==='range'">
      <a-col :span="10">
        <a-input-number style="width: 100%;" v-model:value="modalState.range[0]" placeholder="请输入起始值" />
      </a-col>
      <span style="padding: 0 16px;line-height: 32px;">至</span>
      <a-col :span="10">
        <a-input-number style="width: 100%;" v-model:value="modalState.range[1]" placeholder="请输入截止值" />
      </a-col>
    </a-row>
    <template #footer>
      <a-button type="primary" @click="onSubmitModal">添加</a-button>
      <a-button @click="() => {openModal(false)}">取消</a-button>
    </template>
  </BasicModal>
</template>
<script setup>
import { useRoute } from 'vue-router'
import { message } from 'ant-design-vue';
import { computed, reactive, ref, onMounted } from 'vue';
import BasicModal from '@/components/Modal/BasicModal.vue';
import { useModal } from "@/components/Modal/useModal";
import { qualificationsGroupPush, qualificationsGroup, profile, editQualificationsGroup, qualifications, editQualifications, delQualificationsByQuestion, delQualificationsGroup, matchQualificationsGroup } from '@/api/survey';
const [register, { actionDialog: openModal }] = useModal({
  title: "设置抽样问题",
  width: 600
});
const modalState = ref({
  id: '', 
  key: '',
  question: undefined,
  questionOptions: [],
  textarea: undefined,
  range: [undefined,undefined],
  checkbox: [],
  tree: []
})
const columns = ref([{
  title: '配额组ID',
  dataIndex: 'id',
  width: 100,
}, {
  title: '条件',
  dataIndex: 'questions',
}, {
  title: '匹配会员数',
  dataIndex: 'matchCount',
  width:120
}, {
  title: '目标数量',
  dataIndex: 'requiredCompletes',
  width:240
}, {
  title: '已完成数量',
  dataIndex: 'completes',
  width:120
},{
  title: '操作',
  dataIndex: 'operation',
  width:200
}]);
const dataSource = ref([]);
const editableData = reactive({});
const selectedRowKeys = ref([]);
const onSelectChange = (keys) => {
  selectedRowKeys.value = keys
}
const route = useRoute()
const getGroupDetail = (key) => {
  qualifications(key).then(res => {
    const dist = dataSource.value.find(item => item.key === key)
    const questions = dist.questions.filter(i => i.key)
    res.data.forEach(item => {
      if (item.questionId === 3828) {
        const result = {}
        result.label = `${item.questionName}：${item.parentId}~${item.answerId}`
        result.qid = item.questionId
        questions.push(result)
        return;
      }
      const q = questions.find(i => i.qid === item.questionId)
      if (q) {
        q.label += `、${item.answerName}`
      } else {
        const result = {}
        result.label = `${item.questionName}：${item.answerName}`
        result.qid = item.questionId
        questions.push(result)
      }
    })
    dataSource.value.find(item => item.key === key).questions = questions
  })
}
onMounted(() => {
  qualificationsGroup(route.query.tid).then(res => {
    dataSource.value = res.data.map(item => {
      getGroupDetail(item.id)
      const questions = []
      if (item.excludeMobiles) {
        questions.push({ label: `排除手机号：${item.excludeMobiles}`, key: 'excludeMobiles' })
      }
      if (item.excludeTitles) {
        questions.push({ label: `排除职称：${item.excludeTitles}`, key: 'excludeTitles' })
      }
      if (item.excludeUids) {
        questions.qush({ label: `排除用户id：${item.excludeUids}`,key: 'excludeUids' })
      }
      if (item.specifyHospital) {
        questions.push({ label: `指定医院：${item.specifyHospital}`, key: 'specifyHospital' })
      }
      if (item.specifyMobiles) {
        questions.push({ label: `指定手机号：${item.specifyMobiles}`, key: 'specifyMobiles' })
      }
      if (item.specifyUids) {
        questions.push({ label: `指定用户id：${item.specifyUids}`, key: 'specifyUids' })
      }
      return { ...item, key: item.id, questions }
    })
  })
  profile().then(res => {
    modalState.value.questionOptions = res.data.filter(i=>i.id !== 3803).map(item => {
      let type = 'textarea'
      let list = []
      if (item.list.length > 0) {
        if (item.list.find(i => Array.isArray(i.list))) {
          type = 'tree'
          list = item.list
        } else {
          type = 'checkbox'
          list = item.list.map(i => ({label: i.name, value: i.id}))
        }
      } else if (item.id === 3828){
        type = 'range'
      }
      return {
        ...item,
        type,
        list
      }
    })
  })
})
const modalOptions = computed(() => {
  if (!modalState.value.question) return []
  const dist = modalState.value.questionOptions.find(i => i.id === modalState.value.question)
  return dist.list
});
const modalType = computed(() => {
  if (!modalState.value.question) return ''
  const dist = modalState.value.questionOptions.find(i => i.id === modalState.value.question)
  return dist.type
});
const setInitModal = () => {
  modalState.value.textarea = ''
  modalState.value.range = ['','']
  modalState.value.checkbox = []
  modalState.value.tree = []
}
const onOpenModal = (key,id) => {
  modalState.value.key = key
  modalState.value.id = id
  modalState.value.question = undefined
  setInitModal()
  openModal(true)
}
const onSubmitModal = async () => {
  if (!modalState.value.question) {
    message.error('请选择抽样问题')
    return;
  }
  if (modalType.value === 'textarea' && !modalState.value.textarea) {
    message.error('请输入')
    return;
  }
  if (modalType.value === 'range') {
    if (!modalState.value.range[0] || !modalState.value.range[1]) {
      message.error('请输入范围')
      return;
    } else if (modalState.value.range[0] > modalState.value.range[1]) {
      message.error('起始值必须小于截止值')
      return;
    }
  }
  if (modalType.value === 'checkbox' && modalState.value.checkbox.length === 0) {
    message.error('请选择')
    return;
  }
  if (modalType.value === 'tree' && modalState.value.tree.length === 0) {
    message.error('请选择')
    return;
  }
  let id = modalState.value.id
  if (!id) {
    const res1 = await editQualificationsGroup(route.query.tid, {})
    id = res1.data
    editableData[modalState.value.key].key = res1.data
    editableData[modalState.value.key].id = res1.data
    editableData[res1.data] = editableData[modalState.value.key]
    delete editableData[modalState.value.key]
  }
  const req = []
  if (modalType.value === 'textarea') {
    const adminSurveyQualificationsGroupDto = {
      id
    }
    const result = {}
    if (modalState.value.question === 3829) {
      adminSurveyQualificationsGroupDto.specifyUids = modalState.value.textarea
      result.label = `指定用户id：${modalState.value.textarea}`
      result.key = 'specifyUids'
    } else if (modalState.value.question === 3830) {
      adminSurveyQualificationsGroupDto.specifyMobiles = modalState.value.textarea
      result.label = `指定手机号：${modalState.value.textarea}`
      result.key = 'specifyMobiles'
    } else if (modalState.value.question === 3831) {
      adminSurveyQualificationsGroupDto.specifyHospital = modalState.value.textarea
      result.label = `指定医院：${modalState.value.textarea}`
      result.key = 'specifyHospital'
    } else if (modalState.value.question === 3832) {
      adminSurveyQualificationsGroupDto.excludeUids = modalState.value.textarea
      result.label = `排除用户id：${modalState.value.textarea}`
      result.key = 'excludeUids'
    } else if (modalState.value.question === 3833) {
      adminSurveyQualificationsGroupDto.excludeMobiles = modalState.value.textarea
      result.label = `排除手机号：${modalState.value.textarea}`
      result.key = 'excludeMobiles'
    } else if (modalState.value.question === 3834) {
      adminSurveyQualificationsGroupDto.excludeTitles = modalState.value.textarea
      result.label = `排除职称：${modalState.value.textarea}`
      result.key = 'excludeTitles'
    }
    editQualificationsGroup(route.query.tid, { adminSurveyQualificationsGroupDto }).then(() => {
      message.success('提交成功')
      dataSource.value.find(item => item.key === modalState.value.key).questions.push(result)
      openModal(false)
    })
    return
  }
  if (modalType.value === 'checkbox') {
    modalState.value.checkbox.forEach(key => {
      req.push({
        questionId: modalState.value.question,
        answerId: key
      })
    })
  } else if (modalType.value === 'tree') {
    modalOptions.value.forEach(item => {
      const dist = modalState.value.tree.find(i => i === item.id)
      // 一级数据
      if (dist) {
        req.push({
          questionId: modalState.value.question,
          answerId: dist
        })
      } else {
        item.list.forEach(sub => {
          const subDist = modalState.value.tree.find(i => i === sub.id)
          if (subDist) {
            req.push({
              questionId: modalState.value.question,
              answerId: subDist,
              parentId: item.id
            })
          }
        })
      }
    })
  } else if (modalType.value === 'range') {
    req.push({
      questionId: modalState.value.question,
      answerId: modalState.value.range[1],
      parentId: modalState.value.range[0]
    })
  }
  editQualifications(id, req).then(() => {
    message.success('提交成功')
    getGroupDetail(id)
    openModal(false)
  })
}
const onDeleteQuestion = async (key, index) => {
  const qa = editableData[key].questions[index]
  if (qa.key) {
    await editQualificationsGroup(route.query.tid, {id:key, [qa.key]:''})
  } else {
    await delQualificationsByQuestion(qa.qid)
  }
  message.success('删除成功')
  editableData[key].questions.splice(index, 1)
}
const onEdit = key => {
  editableData[key] = dataSource.value.filter(item => key === item.key)[0]
};
const onPush = key => {
  qualificationsGroupPush(key).then(() => {
    message.success('推送成功')
  })
}
const onBatchPush = () => {
  qualificationsGroupPush(selectedRowKeys.value.join(',')).then(() => {
    message.success('推送成功')
    selectedRowKeys.value = []
  })
}
const onSave = (key) => {
  if (editableData[key].questions.length <= 0) {
    message.error('请添加条件')
    return
  }
  const req = { requiredCompletes: editableData[key].requiredCompletes, id: key }
  editQualificationsGroup(route.query.tid, req).then(() => {
    message.success('保存成功')
    delete editableData[key];
  })
};
const onDelete = key => {
  delQualificationsGroup(key).then(() => {
    message.success('删除成功')
    dataSource.value = dataSource.value.filter(item => item.key !== key);
  })
};
const onAdd = () => {
  const newData = {
    key: `${new Date().getTime()}`,
    requiredCompletes: undefined,
    questions: []
  };
  editableData[newData.key] = newData
  dataSource.value.push(newData);
};
const onMatch = (key) => {
  matchQualificationsGroup(key).then(() => {
    message.success('匹配成功')
  })
}
</script>
<style lang="less">
.btn{
  margin-left: 12px;
}
.flex{
  display: flex;
  width: 100%;
  margin: 10px 0;
  justify-content: space-between;
}
.title{
  font-size: 16px;
  font-weight: bold;
}
</style>